﻿using System;

using SBPweb.RIA.Shared.Contracts.Events;

namespace SBPweb.RIA.Shared.Contracts.Components
{

    public abstract class InitializableBase : IInitializable, IDisposable
    {

        #region Property accessors

        public bool IsInitialized
        {
            get;
            private set;
        }

        #endregion

        #region Events

        public event EventHandler<CancelEventArgs> Initializing;

        public event EventHandler Initialized;

        public event EventHandler<CancelEventArgs> Terminating;

        public event EventHandler Terminated;

        #endregion

        #region Methods

        public void Initialize()
        {
            if (Initializing != null)
            {
                CancelEventArgs cea = new CancelEventArgs();
                Initializing(this, cea);
                if (cea.Cancel)
                {
                    return;
                }
            }

            OnInitialize();

            IsInitialized = true;

            if (Initialized != null)
            {
                Initialized(this, EventArgs.Empty);
            }
        }

        public void Terminate()
        {
            if (Terminating != null)
            {
                CancelEventArgs cea = new CancelEventArgs();
                Terminating(this, cea);
                if (cea.Cancel)
                {
                    return;
                }
            }

            OnTerminate();

            IsInitialized = false;

            if (Terminated != null)
            {
                Terminated(this, EventArgs.Empty);
            }
        }

        protected abstract void OnInitialize();

        protected abstract void OnTerminate();

        public void Dispose()
        {
            if (IsInitialized)
            {
                Terminate();
            }
        }

        #endregion

    }

}